﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KAsFrame.Common.Extensions
{
    public static class SimpleMapperExtensions
    {
        /// <summary>
        /// 浅映射，不匹配的属性将被忽略
        /// </summary>
        /// <typeparam name="TTarget"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static TTarget SimpleMapTo<TTarget>(this object source)
        {
            Type sourceType = source.GetType();
            Type targetType = typeof(TTarget);
            TTarget target = (TTarget)Activator.CreateInstance(targetType);

            foreach (var targetProp in targetType.GetProperties())
            {
                try
                {
                    var val = sourceType.GetProperty(targetProp.Name)?.GetValue(source);
                    if (val != null)
                    {
                        targetProp.SetValue(target, val);
                    }
                }
                catch { }
            }

            return target;
        }

        /// <summary>
        /// 浅映射，不匹配的属性将被忽略
        /// </summary>
        /// <typeparam name="TTarget"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static TTarget SimpleMapTo<TTarget>(this object source, TTarget target)
        {
            Type sourceType = source.GetType();
            Type targetType = typeof(TTarget);

            foreach (var targetProp in targetType.GetProperties())
            {
                try
                {
                    var val = sourceType.GetProperty(targetProp.Name)?.GetValue(source);
                    if (val != null)
                    {
                        targetProp.SetValue(target, val);
                    }
                }
                catch { }
            }

            return target;
        }
    }
}
